import React, { Fragment, PureComponent } from 'react';
import { Icon, Badge, message } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'react-router-dom';
// import MQTT from 'mqtt';
import {BellOutlined} from '@ant-design/icons';


// @connect(({ common, loading }) => ({
//   common,
//   loading: loading.models.common,
// }))

// const client = {}; // 成功连接MQTT服务器后返回的客户端信息
    // 连接MQTT服务端的基础配置
const connection = {
  host: 'broker.emqx.io', // MQTT服务器IP地址
  port: '8083', // 端口号
  endpoint: '/mqtt', // 默认"/mqtt"，string
  clean: false, // 保留会话
  connectTimeout: 4000, // 超时时间
  reconnectPeriod: 4000, // 重连时间间隔
  // 认证信息
  clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`, // 客户端唯一ID标识
  //username: '用户名', // 用户名和密码根据实际情况而定
  //password: '密码',
  lastWillTopic: 'maker',
  cleanSession: false,
};
// // 订阅主题
// const subscription = {
//   topic: 'testtopic/react', // 主题
//   qos: 0, // 等级
// };

// 发布消息
// const publish = {
//   topic: 'topic',
//   qos: 1, // 等级
//   payload: '{ "msg": "Hello, I am browser." }', // 需要发布的信息，格式为字符串或者Arrybuffer
// };
const { host, port, endpoint, ...options } = connection;
const connectUrl = `ws://${host}:${port}${endpoint}`;

// const client = MQTT.connect(connectUrl, options);
// 连接mqtt并订阅
const creatConnectFun = async () => {
  // const { host, port, endpoint, ...options } = connection;
  // const connectUrl = `ws://${host}:${port}${endpoint}`;

  // const client = MQTT.connect(connectUrl, options);

// 客户端连接成功监听事件
  client.on('connect', () => {
    console.log('Connection succeeded!');
  });

// 客户端连接失败监听事件
  client.on('error', (error) => {
    console.log('Connection failed', error);
  });

   // 订阅一个主题
   client.subscribe('testtopic/react', { qos: 2 }, (error) => {
    if (!error) {
        console.log('订阅成功')
    }
})
  // 客户端接收MQTT服务端发布的实时消息
  client.on('message', (topic, message) => {
    console.log('message', message);
    console.log('收到来自', topic, '的消息', message.toString());

   
    // count = Number(count);
    // console.log('count', count);

//     // 接收消息事件
//    client.onMessageArrived = function (message) {
//     console.log('接收消息事件');
//     console.log("接受主题： " + message.destinationName + "的消息： " + message.payloadString);
//     $("#arrivedDiv").append("<br/>"+message.payloadString);
//     var count = $("#count").text();
//     count = Number(count) + 1;
//     $("#count").text(count);
//     console.log('count', count);
// };
  });
   
};
// // 取消订阅
// const cancelconnect = async () => {
//   if (client) {
//     client.end(() => {
//       console.log('取消连接')
//     });
//   }
// }
// @connect(({ common, loading }) => ({
//   common,
//   loading: loading.models.common,
// }))
@connect((state) => ({
  letterCheck: state.letterCheck,
  menu: state.menu,
}))
export default class LetterCheck extends PureComponent {

  state = {
    num: 0 ,// 未读消息数量
    // cloud: 'dftc',
    // cloudName: '东风云',
    // color: "#FF461F",
    // newUrl: '',
    // ifHideIcon: false
  };

  // componentWillUnmount() {
  //   cancelconnect();
  //   // clearTimeout(this.timeout);
  // }
  // credit = false
  componentDidMount() {
    const { dispatch } = this.props
    const {menu: { permissions }} = this.props;
    const isHide = permissions.includes('/creditPlatform/mailManage');
    if(isHide){
    dispatch({
      type: 'letterCheck/getunRead',
      callback: (res) =>{
        if(res.statusCode === "0"){
        sessionStorage.setItem('unreadIds', res.data);
        // creatConnectFun();
        }else{
          // message.warning(res.statusMessage);
        }
      }
    })
  }
  }
  // 点击站内信图标跳转到站内信页面
  clickView = () =>{
    const { dispatch } = this.props;
    console.log('跳转');
    // this.setState({
    //   num: 0
    // })
    dispatch(routerRedux.push({
      pathname: '/creditPlatform/mailManage',
    }));
  }
  render() {
    const {letterCheck: { data }} = this.props;
    console.log('data', typeof(data));
    console.log(data);
    const num = data?.length? data.length : 0;
    // const num = data.length;
    // const record ={
    //   host: 'broker.emqx.io',
    //   clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`,
    //   port: 8083,
    //   username: '',
    //   password: ''
    // }
    // const url = `ws://${record.host}:${record.port}/mqtt`;
    // const options = {
    //   keepalive: 30,
    //   protocolId: 'MQTT',
    //   protocolVersion: 4,
    //   clean: true,
    //   reconnectPeriod: 1000,
    //   connectTimeout: 30 * 1000,
    //   will: {
    //     topic: 'WillMsg',
    //     payload: 'Connection Closed abnormally..!',
    //     qos: 0,
    //     retain: false
    //   },
    //   clientId : record.clientId,
    //   username : record.username,
    //   password : record.password
    // };
    // setClient(mqtt.connect(url, options));
    return (
      <div style={{ display: 'inline', position: 'relative', right: '10px' }}>
        <Fragment>
          <span onClick={this.clickView}>
            <Badge size="small" count={num} style={{ height: '18px', minWidth: '15px' }}>
            <BellOutlined style={{ fontSize: '19px' }}/>
            </Badge>
          </span>
        </Fragment>
      </div>
    )
  }
}
